﻿using AutoMapper;
using Domain.Material_Management;
using Infratructure.Interface;
using MediatR;
using ReturnValue;

namespace MES.Server.API.Application.Command.Material_Management
{
    public class UpdateProductMaterialsHander : IRequestHandler<UpdateProductMaterialsCommand, ApiResult<int>>
    {
        private readonly IRepository<ProductMaterialsModel> productMaterialsRepo;
        private readonly IMapper mapper;
        public UpdateProductMaterialsHander(IRepository<ProductMaterialsModel> productMaterialsRepo, IMapper mapper)
        {
            this.productMaterialsRepo = productMaterialsRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 修改产品物料信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(UpdateProductMaterialsCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();
            var res = await productMaterialsRepo.GetValue(request.Id);
            if (res == null)
            {
                result.Message = "您要修改的信息不存在";
                result.Code = StatusCode.Fail;
                return await Task.FromResult(result);
            }
            else
            {
                res = mapper.Map(request, res);
                res.UpdateTime = DateTime.Now;
                var updateResult = await productMaterialsRepo.UpdateAsync(res);

                if (updateResult > 0)
                {
                    result.Data = updateResult;
                    result.Message = "修改成功";
                    result.Code = StatusCode.Success;
                    return await Task.FromResult(result);
                }
                else
                {
                    result.Message = "修改失败";
                    result.Code = StatusCode.Fail;
                    return await Task.FromResult(result);
                }
            }
        }
    }
}
